import axios from 'axios'
import { ElNotification } from 'element-plus'
import 'element-plus/es/components/notification/style/css'
import { useLoginStore } from '@/stores/login'
import $router from '@/router/index'
//1.实例化axios
var service = axios.create({
    timeout: 10 * 1000,//请求超时时间
    baseURL: 'http://180.76.99.14'//基准路径
})

//2.设置请求拦截器
service.interceptors.request.use(
    (config) => {
        //实例化模块
        var loginStore = useLoginStore()
        //获取token
        var token = loginStore.loginData.token;
        //添加请求头
        config.headers['token'] = token;
        // config.headers['token'] = '';
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
)
//3.设置响应拦截器
service.interceptors.response.use(
    (res) => {
        if (res.data.code == 10119) {
            var loginStore = useLoginStore()
            loginStore.removeLoginData()
            $router.push('/login')
        }
        return res;
    },
    (error: any) => {
        var errorMessage: any = {
            401: '登陆过期,请重新登录!',
            404: '访问路径有误!',
            500: '服务器内部错误',
            503: '服务器不可用'
        }
        ElNotification({
            title: '网络请求通知',
            message: errorMessage[error.response.status],
            type: 'error',
            duration: 1500
        })
        return Promise.reject(error);
    },
)

export default service;